<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form-model ref="form" layout="vertical" :model="mdl" :rules="rules">
                    <a-row>
                        <a-col :span="8">
                            <a-form-model-item :label="i18n('chainDesc','规则描述')" prop="chainDesc">
                                <a-input :placeholder="i18n('chainDesc','请输入规则描述','input')" style="width: 95%"
                                         v-model="mdl.chainDesc"/>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item :label="i18n('chainName','规则别名')" prop="chainName">
                                <a-input :placeholder="i18n('chainName','请输入规则别名','input')"
                                         v-model="mdl.chainName"
                                         style="width: 95%"
                                         @blur="hasChineseAndSpecialChars(mdl.chainName)"/>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item :label="i18n('treeId','分类')" prop="treeId">
                                <rx-category-select
                                    v-model="mdl.treeId"
                                    cat-key="FORM"
                                    style="width: 95%"
                                    :isGrant="true"></rx-category-select>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="24">
                            <a-form-model-item :label="i18n('inParams','入参定义')">
                                <a-form-model-item :label="i18n('type','类型')">
                                    <a-radio-group v-model="inParams.type">
                                        <a-radio value="custom">{{ i18n('custom', '自定义') }}</a-radio>
                                        <a-radio value="form">{{ i18n('form', '表单') }}</a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                                <template v-if="inParams.type=='form'">
                                    <rx-input-button @click="setForm" style="width: 30%"
                                                     v-model="inParams.form"></rx-input-button>
                                </template>
                                <template v-else>
                                    <div class="table-operator">
                                        <a-button @click="addParam('inParamTable')">{{ i18n('addParam', '新增参数') }}
                                        </a-button>
                                        <a-button @click="addSubParam('inParamTable')">
                                            {{ i18n('addSubParam', '新增子参数') }}
                                        </a-button>
                                        <a-button @click="removeParam('inParamTable')">
                                            {{ i18n('removeParam', '删除参数') }}
                                        </a-button>
                                        <a-button @click="importJson('inParamTable')">
                                            {{ i18n('importJson', '导入JSON') }}
                                        </a-button>
                                    </div>
                                    <rx-grid
                                        ref="inParamTable"
                                        :columns="columns"
                                        :dataSource="inParams.params"
                                        :allowRowSelect="true"
                                        :multiSelect="true"
                                        :showPage="false"
                                        :bordered="true"
                                        style="height:270px;"
                                    >
                                  <span slot="paramName" slot-scope="{text,record,index,blur}">
                                    <a-input v-model="record.paramName"/>
                                  </span>
                                        <span slot="paramType" slot-scope="{text,record,index,blur}">
                                    <a-select v-model="record.paramType" :options="typeList">
                                    </a-select>
                                  </span>
                                        <span slot="paramDescp" slot-scope="{text,record,index,blur}">
                                    <a-input v-model="record.paramDescp"/>
                                  </span>
                                        <span slot="value" slot-scope="{text,record,index,blur}">
                                    <a-input v-model="record.value"/>
                                  </span>
                                    </rx-grid>
                                </template>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="24">
                            <a-form-model-item :label="i18n('outParams','出参定义')">
                                <div class="table-operator">
                                    <a-button @click="addParam('outParamTable')">{{ i18n('addParam', '新增参数') }}
                                    </a-button>
                                    <a-button @click="addSubParam('outParamTable')">{{ i18n('addSubParam', '新增子参数') }}
                                    </a-button>
                                    <a-button @click="removeParam('outParamTable')">{{ i18n('removeParam', '删除参数') }}
                                    </a-button>
                                    <a-button @click="importJson('outParamTable')">
                                        {{ i18n('importJson', '导入JSON') }}
                                    </a-button>
                                </div>
                                <rx-grid
                                    ref="outParamTable"
                                    :columns="columns"
                                    :dataSource="outParams"
                                    :allowRowSelect="true"
                                    :multiSelect="true"
                                    :showPage="false"
                                    :bordered="true"
                                    style="height:270px;"
                                >
                                  <span slot="paramName" slot-scope="{text,record,index,blur}">
                                    <a-input v-model="record.paramName"/>
                                  </span>
                                    <span slot="paramType" slot-scope="{text,record,index,blur}">
                                    <a-select v-model="record.paramType" :options="typeList">
                                    </a-select>
                                  </span>
                                    <span slot="paramDescp" slot-scope="{text,record,index,blur}">
                                    <a-input v-model="record.paramDescp"/>
                                  </span>
                                    <span slot="value" slot-scope="{text,record,index,blur}">
                                    <a-input v-model="record.value"/>
                                  </span>
                                </rx-grid>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormLiteFlowApi from '@/api/form/core/formLiteFlow'
import {RxDialog, RxGrid, BaseFormModel, Dialog, RxMonacoEditor, RxInputButton,Util} from "@lowcode/jpaas-common-lib";
import SysInterfaceApiImportJson from "@/views/modules/system/core/SysInterfaceApiImportJson";

export default {
    name: 'FormLiteComponentEdit',
    mixins: [BaseFormModel],
    components: {
        RxDialog,
        RxGrid,
        RxInputButton,
        RxMonacoEditor
    },
    data() {
        return {
            mdl: {
                treeId: "",
                chainDesc: "",
                chainName: "",
                enabled: 0,
                inParams: "",
                outParams: "",
            },
            bean: "",
            rules: {
                chainDesc: [{required: true, message: this.i18n('chainDesc', '请输入规则描述', 'input'), trigger: 'change'}],
                chainName: [
                    {required: true, message: this.i18n('chainName', '请输入规则别名', 'input'), trigger: 'change'},
                    {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:this.i18n2('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                ],
                treeId: [{required: true, message: this.i18n('treeId', '请选择分类', 'select'), trigger: 'change'}],
            },
            typeList: [
                {label: this.invokeScriptI18n('type.character', '字符'), value: "string"},
                {label: this.invokeScriptI18n('type.number', '数字'), value: "number"},
                {label: this.invokeScriptI18n('type.dateType', '日期型'), value: "date"},
                {label: this.invokeScriptI18n('type.boolean', '布尔型'), value: "boolean"},
                {label: this.invokeScriptI18n('type.objectType', '对象型'), value: "object"}
            ],
            columns: [
                {
                    title: this.i18n('paramName','参数名'),
                    dataIndex: 'paramName',
                    width: 100,
                    scopedSlots: {customRender: 'paramName'}
                },
                {
                    title: this.i18n('paramType','参数类型'),
                    dataIndex: 'paramType',
                    width: 100,
                    scopedSlots: {customRender: 'paramType'}
                },
                {
                    title: this.i18n('paramDesc','参数说明'),
                    dataIndex: 'paramDescp',
                    width: 100,
                    scopedSlots: {customRender: 'paramDescp'}
                },
                {
                    title: this.i18n('paramVal','参数值'),
                    dataIndex: 'value',
                    width: 100,
                    scopedSlots: {customRender: 'value'}
                }
            ],
            //入参
            inParams: {
                type: "custom",
                form: "",
                boDefId: "",
                params: [],
            },
            //出参
            outParams: [],
        }

    },
    methods: {
        i18n2(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "formLiteFlow", key);
        },
        invokeScriptI18n(name, text, key) {
            return this.$ti18(name, text, "formInvokeScript", key);
        },
        onload_(values) {
           if(!values){
               return;
           }
            if (values.inParams) {
                this.inParams = JSON.parse(values.inParams);
            }
            if (values.outParams) {
                this.outParams = JSON.parse(values.outParams);
            }
        },
        get(id) {
            return FormLiteFlowApi.get(id);
        },
        save(_, vm) {
            vm.loading = false;
            if (this.hasChineseAndSpecialChars(this.mdl.chainName)) {
                return;
            }
            if (this.inParams) {
                this.mdl.inParams = JSON.stringify(this.inParams)
            }
            if (this.outParams && this.outParams.length > 0) {
                this.mdl.outParams = JSON.stringify(this.outParams)
            }
            return FormLiteFlowApi.save(this.mdl);
        },
        hasChineseAndSpecialChars(str) {
            if (!str) {
                return false;
            }
            //校验特殊字符
            const regexChineseAndSpecialChars = /[\u4e00-\u9fff]|[!@#$%^&*()+\-=\[\]{};':"\\|,.<>\/?]/g;
            const hasChineseOrSpecialChars = regexChineseAndSpecialChars.test(str);
            if (hasChineseOrSpecialChars) {
                this.$message.warning(this.i18n('identifiers','标识中不能包含中文以及特殊字符~'));
                return true;
            }
            return false;
        },
        addParam(table) {
            this.$refs[table].addRow();
        },
        addSubParam(table) {
            let _table = this.$refs[table];
            var row = _table.getSelectedRow();
            if (!row) {
                this.$message.warning(this.invokeScriptI18n('content.isLine', '"请选择一行!'));
                return;
            }
            if (row.paramType != 'object') {
                this.$message.warning(this.invokeScriptI18n('content.isObject', '"请选择类型为对象型的参数!'));
                return;
            }
            var ary;
            if (row.children) {
                ary = row.children;
            } else {
                ary = row.children = [];
            }
            _table.addItem(ary, {parentId: row['idx_']});
            _table.$forceUpdate();
        },
        removeParam(table) {
            this.$refs[table].removeRows();
        },
        setForm(vm) {
            var self = this;
            Dialog.openFormDialog(
                {
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    max: true,
                    data: {
                        params: {
                            Q_deployed__I_EQ: '1',
                        },
                    },
                }, function (data) {
                    vm.setVal(data.alias, data.name);
                    self.inParams.boDefId = data.bodefId;
                }
            )
        },
        importJson(type){
            let self = this;
            Util.open({
                component: SysInterfaceApiImportJson,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: self.i18n('importJson', '导入JSON')
            }, function (action, data) {
                if (action != 'ok') {
                    return;
                }
                if(type == "inParamTable"){
                    self.inParams.params = self.parseDataJson(data);
                }else if(type == "outParamTable"){
                    self.outParams = self.parseDataJson(data);
                }
            });
        },
        parseDataJson(data, paramName, parentId) {
            let result = [];
            if(!data){
                return result;
            }
            let obj = {
                paramName: paramName,
                paramType: '',
                paramDescp: paramName,
                value: '',
                idx_: Util.randomId()
            }
            if(parentId){
                obj.parentId = parentId;
            }
            if(data){
                if (data.constructor == Object) {
                    obj.paramType = 'object';
                    obj.children = [];
                    for (let key in data) {
                        if(obj.paramName){
                            obj.children.push(...this.parseDataJson(data[key],key, obj.idx_));
                        }else {
                            result.push(...this.parseDataJson(data[key],key, obj.idx_));
                        }
                    }
                }else if(data.constructor == Array){
                    obj.paramType = 'array';

                } else if (data.constructor == Number) {
                    obj.paramType = 'number';
                    obj.value = data;
                } else if (data.constructor == Boolean) {
                    obj.paramType = 'boolean';
                    obj.value = data;
                }else {
                    obj.paramType = 'string';
                    obj.value = data;
                }
            }
            if(obj.paramName){
                result.push(obj);
            }
            return result;
        },
    }
}
</script>
<style>
.relick a {
    margin-right: 10px;
}

</style>
